<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.productMaterialConfig_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productMaterialConfig_delete" @click="handleDelete">删 除 </el-button>
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.productMaterialConfig_view" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.productMaterialConfig_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.productMaterialConfig_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog
      v-dragDirectives
      ref="dialog"
      :title="dialogTitle"
      append-to-body
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="5vh"
      width="70%"
      @close="closeDialog"
    >
      <avue-form ref="basicInfoForm" v-if="showDialog" v-model="form" :option="dialogOption"></avue-form>
      <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>关键料追溯配置表</h3>
      <el-row style="margin-bottom: 10px">
        <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="openSectionSelect('part')">添加物料</el-button>
        <el-button v-if="dialogTitle != '详情'" type="primary" size="small" @click="openSectionSelect('bom')">添加BOM</el-button>
        <el-button v-if="dialogTitle != '详情'" type="danger" size="small" icon="el-icon-delete" @click="productInfoDelete">删 除</el-button>
      </el-row>
      <el-table v-loading="loading" ref="productInfoCrud" height="500px" :data="productInfoList" border style="width: 100%" @selection-change="basicInfoSelectionChange">
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" width="50" align="center"></el-table-column>
        <el-table-column v-for="item in productInfoOption.column" :label="item.label" :prop="item.prop" :key="item.prop">
          <template slot-scope="scope">
            <span v-if="item.prop === 'quantity'">
              <el-input-number v-model="scope.row.quantity" name="quantity" :controls="false" style="width: 100%" :disabled="dialogTitle == '详情'"></el-input-number>
            </span>
            <span v-else-if="item.prop === 'sectionId'">
              <el-select v-model="scope.row.sectionId" placeholder="请选择" :disabled="dialogTitle == '详情'">
                <el-option v-for="item in workSectionList" :key="item.sectionId" :label="item.sectionName" :value="item.sectionId"> </el-option>
              </el-select>
            </span>
            <span v-else-if="item.prop === 'isReplaceable'">
              {{ scope.row.isReplaceable === true ? '有' : '无' }}
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" v-if="dialogTitle != '详情'">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="productInfoRowDel(scope.row, scope.$index)">删除</el-button>
            <el-button size="small" type="text" @click="handleTimeControl(scope.row, scope.$index)">时效管控</el-button>
            <el-button type="text" size="small" @click="handleAddMaterial(scope.row, scope.$index)">添加替代料</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit"><i class="el-icon-circle-check"></i><span>修 改</span> </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!-- 添加物料 -->
    <addMaterialDialog v-if="showMaterialDialog" ref="material" :visible.sync="showMaterialDialog" :productInfoList="productInfoList"></addMaterialDialog>
    <!-- 添加BOM -->
    <addBomDialog v-if="showBomDialog" ref="addBom" :visible.sync="showBomDialog" :productInfoList="productInfoList"></addBomDialog>
    <el-dialog title="请选择用料工段" :visible.sync="showSelectSectionDialog" width="30%" append-to-body="true" @close="closeSelectSectionDialog">
      <avue-form ref="selectSectionDialogForm" :option="selectSectionOption" v-model="selectSectionDialogForm"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-check" @click="openCommonModal">确 定</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="showSelectSectionDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :key="timer" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.importUrl"
      :formData="importConfig.formData"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
  </basic-container>
</template>
<script>
import { getList, getDetail, addOrUpdate, remove, getSectionByPartId, getValidateSationList } from '@/api/product/product-material-config';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { getList as getBomList, getReplacementList } from '@/api/admin/bom';
import TimelyControlDialog from '@/views/product/components/timelyControlDialog';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import addMaterialDialog from '@/views/product/components/addMaterial.vue';
import addBomDialog from '@/views/product/components/addBom.vue';
import importDialogComp from '@/components/dialog/import/index.vue';
export default {
  name: 'ProductProductMaterialConfig',
  components: {
    TimelyControlDialog,
    CommonModalTemplate,
    userTableConfig,
    addMaterialDialog,
    addBomDialog,
    importDialogComp
  },
  mixins: [userConfig()],
  data() {
    var validateQuantity = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入单位用量'));
      } else {
        if (value <= 0) {
          callback(new Error('单位用量不能小于等于0'));
        } else {
          callback();
        }
      }
    };
    return {
      pageCode: 'PRODUCT_MATERIAL_CONFIG',
      form: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        menuWidth: 200, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            disabled: false
          },
          {
            label: '产品类型',
            prop: 'partType',
            type: 'select',
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            search: true
          },
          {
            label: '创建人',
            prop: 'createUserName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          }
        ]
      },
      dialogTitle: '新增',
      showDialog: false,
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '80',
        column: [
          {
            label: '产品编码',
            prop: 'productPartNo',
            type: 'search',
            span: 8,
            labelWidth: '85',
            placeholder: '请选择 产品编码',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              if (this.dialogTitle === '新增') {
                this.openProductCommonModal();
              }
            }
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            span: 8,
            disabled: true
          },
          {
            label: '产品类型',
            prop: 'partType',
            type: 'select',
            span: 8,
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            disabled: true
          }
        ]
      },
      data: [],
      productInfoOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        cellBtn: true,
        menuWidth: 280,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '单位用量',
            prop: 'quantity',
            cell: true,
            type: 'number',
            rules: [{ validator: validateQuantity, trigger: 'blur' }]
          },
          {
            label: '用料工段',
            prop: 'sectionId',
            cell: true,
            type: 'select',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请输入用料工段',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否存在替代料',
            prop: 'isReplaceable',
            type: 'select',
            dicData: [
              {
                label: '无',
                value: false
              },
              {
                label: '有',
                value: true
              }
            ],
            cell: false
          },
          // {
          //   label: 'json',
          //   prop: 'replacementPartnos',
          //   cell: false,
          //   hide: true
          // },
          {
            label: '替代料编码',
            prop: 'replacementPartCode',
            cell: false,
            hide: false
          },
          {
            label: '替代料型号',
            prop: 'replacementPartModel',
            cell: false,
            hide: false
          }
        ]
      },
      productInfoList: [],
      productInfoKey: 'init',
      tableOption: {},
      timer: new Date().getTime(),
      basicInfoSelectionList: [],
      processId: '', //工艺ID,
      workSectionList: [],
      materialControlsDeleteIds: [],
      selectTimeControlIndex: 0,
      showSelectSectionDialog: false,
      addPartType: '',
      selectSectionDialogForm: {},
      selectSectionOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '用料工段',
            type: 'select',
            span: 24,
            prop: 'sectionId',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择用料工段',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      showMaterialDialog: false,
      showBomDialog: false,
      importConfig: {
        show: false,
        importUrl: '/api/mes-product/material/control/header/import',
        exportName: '关键料导入模版.xlsx',
        formData: {
          req: []
        },
        title: '关键料导入'
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    basicInfoIndex() {
      let indexs = [];
      this.basicInfoSelectionList.forEach((ele) => {
        indexs.push(ele.$index);
      });
      return indexs;
    }
  },
  methods: {
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this._forEach(this.data, (item) => {
          item.status = String(item.status);
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = false;
      });
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.basicInfoForm.validate((valid, done) => {
        if (valid) {
          if (this.productInfoList.length === 0) {
            this.$message({
              type: 'warning',
              message: '请添加产品生产用量！'
            });
            return;
          }
          console.log(this.productInfoList, 999, this.productInfoList);
          for (let i = 0; i < this.productInfoList.length; i++) {
            if (!this.productInfoList[i].quantity && this.productInfoList[i].quantity != 0 && this.productInfoList[i].partSubType !== 'INDIRECT') {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的单位用量不能为空！`
              });
              return;
            }
            if (this.productInfoList[i].quantity <= 0) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的单位用量不能小于等于0！`
              });
              return;
            }
            if (!this.productInfoList[i].sectionId) {
              this.$message({
                type: 'warning',
                message: `物料编码为${this.productInfoList[i].partNo}的用料工段不能为空！`
              });
              return;
            }
            for (let j = i + 1; j < this.productInfoList.length; j++) {
              if (this.productInfoList[i].partNo === this.productInfoList[j].partNo && this.productInfoList[i].sectionId === this.productInfoList[j].sectionId) {
                this.$message({
                  type: 'warning',
                  message: `多个物料编码为${this.productInfoList[i].partNo}的用料工段不能被重复选择！`
                });
                return;
              }
            }
          }
          let params = {};
          if (this.dialogTitle === '新增') {
            let materialControls = [];
            this._forEach(this.productInfoList, (item, index) => {
              let workSectionObj = this._find(this.workSectionList, { sectionId: item.sectionId });
              console.log(workSectionObj);
              let params = {
                keyMaterialConfigId: item.partMasterId,
                sequence: index + 1,
                partNo: item.partNo,
                partName: item.partName,
                partModel: item.partModel,
                quantity: item.quantity,
                sectionId: item.sectionId,
                sectionName: workSectionObj ? workSectionObj.sectionName : '',
                isReplaceable: item.isReplaceable,
                replacementPartnos: item.replacementPartnos,
                timeConditions: item.timeConditions
              };
              materialControls.push(params);
            });
            params = {
              type: 'PRODUCT',
              partMasterId: this.form.partMasterId,
              productPartNo: this.form.productPartNo,
              productPartName: this.form.productPartName,
              productPartModel: this.form.productPartModel,
              keyMaterialConfigDetailDtoList: materialControls
            };
          } else {
            this._forEach(this.productInfoList, (item, index) => {
              item.sequence = index + 1;
              item.processId = this.processId;
              item.controlType = 'ROUTE';
              item.subType = 'PRODUCT';
              let workSectionObj = this._find(this.workSectionList, { sectionId: item.sectionId });
              item.partMasterSectionId = workSectionObj ? workSectionObj.id : '';
            });
            params = this.form;
            params.keyMaterialConfigDetailDtoList = this.productInfoList;
            // params.materialControlsDeleteIds = this.materialControlsDeleteIds;
          }
          addOrUpdate(params).then(
            (res) => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              this.showDialog = false;
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.form.partType = row.partType;
        this.productInfoOption.menu = false;
        getSectionByPartId(row.partMasterId).then((res) => {
          let data = this._get(res, 'data.data.sections', []);
          if (data != null) {
            this.workSectionList = data;
          } else {
            this.workSectionList = [];
          }

          this.productInfoList = this._get(this.form, 'details', []);
          this._forEach(this.productInfoList, (item) => {
            try {
              item.replacementPartCode = item.replacementPartnos ? (JSON.parse(item.replacementPartnos) || []).map((item) => item.partCode).join(',') : '';
              item.replacementPartModel = item.replacementPartnos ? (JSON.parse(item.replacementPartnos) || []).map((item) => item.partModel).join(',') : '';
            } catch (error) {
              console.log('error', error);
            }
          });
        });
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = true;
      });
      this.productInfoOption.menu = true;
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        getSectionByPartId(row.partMasterId).then((res) => {
          let data = this._get(res, 'data.data.sections', []);
          if (data != null) {
            this.workSectionList = data;
          } else {
            this.workSectionList = [];
          }
          this.productInfoList = this._get(this.form, 'details', []);
          this._forEach(this.productInfoList, (item) => {
            item.partMasterId = item.partMasterId;
            try {
              item.replacementPartCode = item.replacementPartnos ? (JSON.parse(item.replacementPartnos) || []).map((item) => item.partCode).join(',') : '';
              item.replacementPartModel = item.replacementPartnos ? (JSON.parse(item.replacementPartnos) || []).map((item) => item.partModel).join(',') : '';
            } catch (error) {
              console.log('error', error);
            }
          });
        });
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    closeDialog() {
      this.$refs.basicInfoForm.resetFields();
      this.form = {};
      this.productInfoList = [];
      this.materialControlsDeleteIds = [];
      let workSectionIdColumn = this.findObject(this.productInfoOption.column, 'sectionId');
      workSectionIdColumn.dicData = [];
    },
    /**
     * 打开物料选择模态框
     */
    openProductCommonModal() {
      this.modalName = 'productModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '物料类型',
            prop: 'partType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    openSectionSelect(type) {
      if (!this.form.productPartNo) {
        this.$message({
          type: 'warning',
          message: '请先选择产品编码！'
        });
        return;
      }
      if (type == 'part') {
        this.showMaterialDialog = true;
        this.$nextTick(() => {
          this.$refs.material.initData(this.workSectionList);
        });
      }
      if (type == 'bom') {
        this.showBomDialog = true;
        this.$nextTick(() => {
          let partInfo = {
            partNo: this.form.productPartNo,
            partName: this.form.productPartName,
            partModel: this.form.partductPartModel
          };
          this.$refs.addBom.initData(this.workSectionList, [partInfo]);
        });
      }
    },
    openCommonModal() {
      if (!this.selectSectionDialogForm.sectionId) {
        this.$message.warning('请选择用料工段!');
        return;
      }
      if (this.addPartType === 'part') {
        this.addMaterial();
      } else {
        this.addBom();
      }
    },
    closeSelectSectionDialog() {
      this.$refs.selectSectionDialogForm.resetFields();
      this.selectSectionDialogForm = {};
    },
    /**
     * 添加物料
     */
    addMaterial() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料',
        url: '/api/mes-admin/part-master/page?materialAndSemifinished=true',
        isPage: true,
        rowSelectionType: 'multiple',
        isDefaultLoad: true,
        selectOption: {
          isMark: true
        },
        selectable: (row, index) => {
          return !this.productInfoList.map((item) => item.partMasterId).includes(row.id);
        },
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    /**
     * 双击模态框行
     */
    getSelectedRows(row) {
      switch (this.modalName) {
        case 'productModal':
          this.form.productPartId = row.id;
          this.form.productPartNo = row.partNo;
          this.form.productPartName = row.name;
          this.form.partType = row.partType;
          this._forEach(this.productInfoList, (item) => {
            item.sectionId = '';
          });
          getSectionByPartId(this.form.productPartId).then((res) => {
            let data = this._get(res, 'data.data.sections', []);
            if (data != null) {
              this.workSectionList = data;
            } else {
              this.workSectionList = [];
            }
          });
          break;
        case 'partModal':
          this.showSelectSectionDialog = false;
          for (let i = 0; i < row.length; i++) {
            this.productInfoList.push({
              $index: this.productInfoList.length,
              partMasterId: row[i].id,
              partNo: row[i].partNo,
              partName: row[i].name,
              partModel: row[i].partModel,
              quantity: undefined,
              sectionId: this.selectSectionDialogForm.sectionId
            });
          }
          break;
        case 'bomModal':
          this.showSelectSectionDialog = false;
          for (let i = 0; i < row.length; i++) {
            this.productInfoList.push({
              $index: this.productInfoList.length,
              partMasterId: row[i].id,
              partNo: row[i].partNo,
              partName: row[i].name,
              partModel: row[i].partModel,
              quantity: row[i].unitQty,
              sectionId: this.selectSectionDialogForm.sectionId
            });
          }
          break;
        case 'replaceModal':
          const index = this.selectTimeControlIndex;
          const replacementList = row.map((item) => ({
            partNo: item.partNo,
            partName: item.partName,
            rate: item.subsRate
          }));
          this.$set(this.productInfoList[index], 'replacementPartnos', JSON.stringify(replacementList));
          this.$set(this.productInfoList[index], 'replacementPartCode', replacementList.map((item) => item.partCode).join(','));
          this.$set(this.productInfoList[index], 'replacementPartModel', replacementList.map((item) => item.partModel).join(','));
          this.$set(this.productInfoList[index], 'isReplaceable', row.length > 0);
          this.productInfoKey = new Date().getTime();
          break;
        default:
          break;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    productInfoRowClick(row) {
      this.rowIndex = row.$index;
    },
    productInfoRowSave(form, done) {
      done();
    },
    productInfoRowUpdate(form, index, done) {
      done();
    },
    productInfoRowDel(row, index) {
      this.productInfoList.splice(index, 1);
      if (row.id) {
        this.materialControlsDeleteIds.push(row.id);
      }
    },
    basicInfoSelectionChange(list) {
      this.basicInfoSelectionList = list;
    },
    productInfoDelete() {
      if (this.basicInfoSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let selectList = [];
        this.materialControlsDeleteIds = [];
        this._forEach(this.basicInfoIndex, (item) => {
          selectList.push(this.productInfoList[item]);
          if (this.productInfoList[item].id) {
            this.materialControlsDeleteIds.push(this.productInfoList[item].id);
          }
        });
        this._forEach(selectList, (item) => {
          let index = this.productInfoList.indexOf(item);
          this.productInfoList.splice(index, 1);
        });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.$refs.productInfoCrud.clearSelection();
      });
    },

    // 添加替代料
    async handleAddMaterial(row, index) {
      this.selectTimeControlIndex = index;
      const params = {
        bomPartNo: this.form.productPartNo,
        bomDetailPartNo: row.partNo
      };
      getBomList(1, 10000, { productPartNo: this.form.productPartNo, sourceType: 'ERP', isAll: true }).then((res) => {
        let bomList = this._get(res, 'data.data.records', []);
        if (bomList.length > 0) {
          bomList = this._map(bomList, (item) => {
            return {
              label: item.bomVersion,
              value: item.id
            };
          });
          let bomId = this._get(bomList, '[0].value', '');
          this.openReplacement(params, { bomId, bomList });
        } else {
          this.$message({
            type: 'warning',
            message: '请先配置相应的产品BOM！'
          });
        }
      });
    },
    // 添加BOM
    addBom() {
      getBomList(1, 10000, { productPartNo: this.form.partNo, sourceType: 'ERP', isAll: true }).then((res) => {
        let bomList = this._get(res, 'data.data.records', []);
        if (bomList.length > 0) {
          bomList = this._map(bomList, (item) => {
            return {
              label: item.bomVersion,
              value: item.id
            };
          });
          let bomId = this._get(bomList, '[0].value', '');
          this.openBomPart(bomList, bomId);
        } else {
          this.$message({
            type: 'warning',
            message: '请先配置相应的产品BOM！'
          });
        }
      });
    },
    openReplacement(query, { bomId, bomList }) {
      this.modalName = 'replaceModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '添加替代料',
        url: '/api/mes-admin/bom/part/replacement/list',
        isPage: true,
        index: true,
        selection: true,
        emptyBtn: false,
        query,
        tableTitle: '替代料',
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: 'BOM版本',
            search: true,
            clearable: false,
            searchClearable: false,
            type: 'select',
            prop: 'bomId',
            dicData: bomList,
            searchValue: bomId,
            hide: true,
            searchLabelWidth: 90,
            searchRules: [
              {
                required: true,
                message: '请先选择BOM版本',
                trigger: 'change'
              }
            ]
          },
          {
            label: '名称',
            prop: 'replacePartName',
            search: true
          },
          {
            label: '编码',
            prop: 'replacePartNo',
            search: true
          },
          {
            label: '类型',
            prop: 'replacePartType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
          },
          {
            label: '型号',
            prop: 'replacePartModel'
          },
          {
            label: '用量',
            prop: 'replaceQuantity'
          }
        ]
      };
    },
    openBomPart(bomList, bomId) {
      this.modalName = 'bomModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择BOM物料信息（双击进行选择）',
        url: '/api/mes-admin/bom/detail/part-page',
        isPage: true,
        index: true,
        selection: true,
        selectOption: {
          isMark: true
        },
        selectable: (row, index) => {
          return !this.productInfoList.map((item) => item.partMasterId).includes(row.id);
        },
        isDefaultLoad: true,
        // tableTitle: '替代料',
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '用量',
            prop: 'unitQty'
          },
          {
            label: 'BOM版本',
            prop: 'bomId',
            search: true,
            type: 'select',
            dicData: bomList,
            searchValue: bomId,
            hide: true
          }
        ]
      };
    },
    handleImport() {
      this.importConfig.show = true;
    },
    codeClose(value, data, fileParams) {}
  }
};
</script>
<style lang="scss" scoped>
.custom-title {
  font-size: 16px;
  font-weight: bold;
  .mr10 {
    margin-right: 10px;
  }
}
::v-deep .el-table__header {
  thead {
    th {
      background-color: #fafafa;
      padding: 8px 0;
      color: rgba(0, 0, 0, 0.85);
      font-size: 12px;
    }
  }
}
</style>
